package com.xunqi.usercenter.service.impl;

import com.xunqi.common.dto.user.UserAddBonusMsgDTO;
import com.xunqi.common.dto.user.UserLoginDTO;
import com.xunqi.common.entity.user.BonusEventLog;
import com.xunqi.common.entity.user.User;
import com.xunqi.usercenter.dao.BonusEventLogDao;
import com.xunqi.usercenter.dao.UserDao;
import com.xunqi.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @Description:
 * @Created with IntelliJ IDEA.
 * @author: 夏沫止水
 * @create: 2020-04-17 10:46
 **/
@Service("userService")
@Slf4j
public class UserServiceImpl implements UserService {

    @Resource
    private UserDao userDao;

    @Resource
    private BonusEventLogDao bonusEventLogDao;

    @Override
    public User findById(Integer id) {
        return userDao.queryById(id);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addBonus(UserAddBonusMsgDTO userAddBonusMsgDTO) {

        //当收到消息时，执行的业务
        //获取用户id和机房
        Integer userId = userAddBonusMsgDTO.getUserId();
        Integer bonus = userAddBonusMsgDTO.getBonus();

        //查询指定用户
        User user = userDao.queryById(userId);

        //1.为用户加积分
        user.setBonus(user.getBonus() + bonus);
        //更新到数据库中
        int updateResult = userDao.update(user);

        //如果更新失败则return返回
        if (updateResult <= 0) {
            return;
        }


        //2.记录日志到bonus_event_log表里
        BonusEventLog bonusEventLog = BonusEventLog.builder()
                .userId(userId)
                .value(bonus)
                .event(userAddBonusMsgDTO.getEvent())
                .createTime(new Date())
                .description(userAddBonusMsgDTO.getDescription())
                .build();

        int result = bonusEventLogDao.insert(bonusEventLog);

        if (result <= 0) {
            return;
        }

        log.info("积分添加完毕");
    }

    @Override
    public User login(UserLoginDTO loginDTO, String openId) {

        User user = User.builder().wxId(openId).build();

        //根据用户微信id查询用户信息
        List<User> users = userDao.queryAll(user);

        //如果没有查询出来用户就添加一条用户记录，否则直接登录
        if (users == null && users.size() == 0) {
            User userToSave = User.builder()
                    .wxId(openId)
                    //初始化积分
                    .bonus(300)
                    .wxNickname(loginDTO.getWxNickname())
                    .avatarUrl(loginDTO.getAvatarUrl())
                    .roles("user")
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();

            if (userDao.insert(userToSave) > 0) {
                return userToSave;
            }
        }

        return users.get(0);
    }
}
